﻿#Include ..\builtin\exec.ahk
#Include ..\baseHandle.ahk

#Include ..\..\_lib\JSON.ahk

class Chat extends BaseHandle {

  static chatHistory := ''
  static nullable := true

  static Handle(parsed) {
    static mfc := MeowConf.Of('./cfg/misc/chat/chatFile.txt')
    static systemPrompt := getSystemPrompt(mfc.Get('prompt')[mfc.Get('model')])

    q := T_(rq := LTrim(parsed.raw.substring(parsed.which.Length + 1)), ['""', '\\', "''"])
    body := '{"model":"' mfc.Get('model') '","messages": ['
      . '{"role":"system","content":"' systemPrompt '"}'
      . Chat.chatHistory
      . ',{"role": "user","content":"' q '"}'
      . '],"stream":false}'

    echo := Exec.Handle({ target: 'http -X=POST -d=`'' body '`' http://localhost:11434/api/chat' })
    r := JSON.Parse(echo.r)

    Chat.chatHistory .= Format(',{"role":"user","content":"{}"},{"role":"assistant","content":"{}"}'
      , q, T_(r.message.content, ['""', '\\', "''"]))

    Record('user', rq)
    Record(r.message.role, r.message.content)

    Record(role, content) => FileAppend(Format('{}:`n{}`n`n', role, StrReplace(content, '`n`n', '`n'))
      , './cfg/misc/chat/chatHistory.txt', 'utf-8')
    static getSystemPrompt(n) => n && T_(FileRead('./cfg/misc/chat/' n 'Prompt.txt', 'utf-8'), ['""', '\\', "''"])

    return this.succ(r.message.content)
  }

  static Conf() => ToString(MeowConf.Of('./cfg/misc/chat/chatFile.txt').data)

  static Echo() => '
  (
    chat
    chat text
    Ollama接口，已废弃
  )'

}
